package com.itboye.api.domain;

import com.itboye.api.interfaces.IDomainParams;
import com.itboye.api.model.ByInnerResponseData;
import com.itboye.api.model.ByRequestData;
import com.itboye.api.model.ByResponseData;
import com.itboye.system.crypt.ByDataCrypt;
import com.itboye.system.exception.ByBaseException;
import com.itboye.system.helper.ByConsoleHelper;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;

/**
 * 基础领域模型
 * Created by hebidu on 16/5/11.
 */
public class BaseDomain implements IDomainParams {



    protected HttpServletRequest getRequest(){
        try {
            RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
            if (requestAttributes == null) return null;
            if (!(requestAttributes instanceof ServletRequestAttributes)) return null;

            return ((ServletRequestAttributes)requestAttributes).getRequest();

        }catch (IllegalStateException e){
            return null;
        }
    }

    protected  void assertNotNull(Object data,String msg) throws ByBaseException {
        if(data == null) {
            throw  new ByBaseException(msg);
        }
        if(data instanceof String && ((String)data).length() ==0 ){
            throw  new ByBaseException(msg);
        }

    }

    /**
     * 接口操作成功返回
     * @param data 返回内容的加密字符串
     * @return
     * @throws ByBaseException
     */
    protected ByResponseData success(Object data) throws ByBaseException, UnsupportedEncodingException {

//        ByConsoleHelper.debug("返回成功信息" + data.toString(),null);
        ByInnerResponseData innerData = new ByInnerResponseData("0",data,getRequestData().getNotifyId());
        String jsonData = innerData.toJson();
        ByConsoleHelper.debug("成功返回信息json=" + jsonData ,null);

        ByResponseData responseData = ByResponseData.done(true, ByDataCrypt.encodeData(jsonData),getRequestData().getClientSecret(),getRequestData().getNotifyId());

        responseData.setClientId(getRequestData().getClientId());

        return responseData;
    }

    /**
     * 接口操作失败返回
     * @param data 通常是提示信息
     * @return
     * @throws ByBaseException
     */
    protected ByResponseData fail(String failMsg) throws ByBaseException, UnsupportedEncodingException {
        ByConsoleHelper.debug("返回失败信息: " + failMsg,null);
        ByInnerResponseData innerData = new ByInnerResponseData("-1",failMsg,getRequestData().getNotifyId());
        String jsonData = innerData.toJson();
        ByResponseData responseData = ByResponseData.done(false,ByDataCrypt.encodeData(jsonData),getRequestData().getClientSecret(),getRequestData().getNotifyId());

        responseData.setClientId(getRequestData().getClientId());

        return  responseData;
    }


    /**
     * 检测接口版本
     * @param apiVer 字符串,多个以逗号隔开
     */
    public void checkApiVersion(String apiVer) throws ByBaseException {
        String reqApiVer = this.getRequestData().getApiVer();
        if(!apiVer.contains(",")){//单个
            if(reqApiVer.equals(apiVer)){
                return;
            }
        }else {
            //多个
            String[] legalApiVersions = apiVer.split(",");

            for (int i = 0; i < legalApiVersions.length; i++) {
                if (legalApiVersions[i].equals(reqApiVer)) {
                    return;
                }
            }
        }
        throw new ByBaseException("请更新接口,支持版本:"+apiVer);

    }


    /**
     *
     * @param key
     * @return
     */
    public Integer getIntegerParam(String key,Integer defaultValue){
        Object obj = this.getParams().get(key);
        if(obj != null ){
            String strObj =  (String) obj;
            return Integer.parseInt(strObj);
        }

        return defaultValue;
    }


    /**
     *
     * @param key
     * @return
     */
    public Integer getIntegerParam(String key){
        Object obj = this.getParams().get(key);
        if(obj != null ){
            if(obj instanceof String){
                String strObj =  (String) obj;
                return Integer.parseInt(strObj);
            }

            if(obj instanceof Integer){
                return Integer.parseInt(obj.toString());
            }
        }

        return null;
    }


    /**
     *
     * @param key
     * @return
     */
    public String getStringParam(String key,String defaultValue){

        Object obj = this.getParams().get(key);

        if(obj != null){
            return obj.toString();
        }

        return defaultValue;
    }


    /**
     *
     * @param key
     * @return
     */
    public String getStringParam(String key){

        Object obj = this.getParams().get(key);

        if(obj != null){
            return obj.toString();
        }

        return "";
    }

    //多线程情况下
    private ThreadLocal<HashMap> localParamsData = new ThreadLocal<HashMap>();
    private ThreadLocal<ByRequestData> localRequestData = new ThreadLocal<ByRequestData>();


//    private HashMap params;
//    private ByRequestData  requestData;

    public ByRequestData getRequestData() {
        return localRequestData.get();
    }

    public HashMap getParams(){
//        if(params == null){
//            params = new HashMap();
//        }
        return localParamsData.get();
    }

    public void initAllNeedParams(HashMap map, ByRequestData requestData) {
//        this.params = map;
//        this.requestData = requestData;
        localParamsData.set(map);
        localRequestData.set(requestData);
        ByConsoleHelper.debug("BaseDomain 构造函数",null);
    }

    public BaseDomain(){}
}
